<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="copyright" content="All Rights Reserved, Copyright (C) 2013, Wuyeguo, Ltd."/>
    <title>智能应急快速搭建平台V1.0</title>
    <script type="text/javascript" src="../../js/commonCss.js"></script>
    <script type="text/javascript" src="../../js/commonJs.js"></script>
</head>
<div class="easyui-layout" data-options="fit:true">
    <!-- Begin of toolbar -->
    <div id="wu-toolbar-role">
        <div class="wu-toolbar-button">
            <a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="openAdd()" plain="true">添加</a>
            <!--            <a href="#" class="easyui-linkbutton" iconCls="icon-edit" onclick="openEdit()" plain="true">修改</a>-->
            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="remove()" plain="true">删除</a>
        </div>
        <div class="wu-toolbar-search">
            <label>角色名称：</label><input id="search_userName" name="search_userName" class="wu-text" style="width:100px">
            <a href="#" class="easyui-linkbutton" iconCls="icon-search" onclick="doSearch()">开始检索</a>
        </div>
    </div>
    <!-- End of toolbar -->
    <table id="role-datagrid" class="easyui-datagrid" toolbar="#wu-toolbar-role"></table>

</div>
<!-- Begin of easyui-dialog -->
<div id="role-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="role-form" method="post">
        <input type="hidden" name="roleid" id="roleid">
        <table>
            <tr>
                <td width="60" align="right">角色名称:</td>
                <td><input type="text" name="rolename" id="rolename" class="wu-text"/></td>

            </tr>
            <tr>
                <td width="60" align="right">排序号:</td>
                <td><input type="text" name="roledesc" id="roledesc" class="wu-text"/></td>
            </tr>
        </table>
    </form>
</div>

<div id="user-pz-dialog" class="easyui-dialog" data-options="closed:true,iconClls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="user-role-form" method="post">
        <input type="hidden" name="ckdTree" id="ckdTree">
        <table>
            <tr>
                <td><font> 用户选择:</font>
                    <div style="overflow-x: auto; overflow-y: auto;height: 400px; width:350px;" id="userTree"
                         class="ztree">
                    </div>
                </td>
            </tr>
        </table>
    </form>
</div>

<div id="per-pz-dialog" class="easyui-dialog" data-options="closed:true,iconClls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="per-role-form" method="post">
        <input type="hidden" name="ckdPreTree" id="ckdPreTree">
        <table>
            <tr>
                <td><font> 权限选择:</font>
                    <div style="overflow-x: auto; overflow-y: auto;height: 400px; width:350px;" id="perTree"
                         class="ztree">
                    </div>
                </td>
            </tr>
        </table>
    </form>
</div>
<!-- End of easyui-dialog -->
<script type="text/javascript">
    $(function () {

        $("#rolename").validatebox({
            required: true
        });
        $('#showId').combotree();
    });

    /**
     * Name 查询
     */
    function doSearch() {
        $('#role-datagrid').datagrid('load', {paramData: JSON.stringify(searchData())});
    }


    /**
     * Name 添加记录
     */
    function add() {
        save("/role/add");
    }

    /**
     * Name 修改记录
     */
    function edit() {
        save("/role/update");
    }

    /**
     * Name 删除记录
     */
    function remove() {
        $.messager.confirm('信息提示', '确定要删除该记录？', function (result) {
            if (result) {
                var items = $('#role-datagrid').datagrid('getSelections');
                var ids = [];
                $(items).each(function () {
                    ids.push(this.roleid);
                });
                $.ajax({
                    url: '/role/del',
                    data: 'ids=' + ids,
                    success: function (data) {
                        if (data) {
                            $.messager.alert('信息提示', '删除成功！', 'info');
                            $('#role-datagrid').datagrid();
                        } else {
                            $.messager.alert('信息提示', '删除失败！', 'info');
                        }
                    }
                });
            }
        });
    }

    /**
     * Name 打开添加窗口
     */
    function openAdd() {
        $('#role-form').form('clear');
        $('#role-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: add
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#role-dialog').dialog('close');
                }
            }]
        });
        comboTree();
    }

    /**
     * 打开人员选择页面
     */
    function userEdit(id) {
        $('#user-role-form').form('clear');
        $('#user-pz-dialog').dialog({
            closed: false,
            modal: true,
            title: "人员选择",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    onCheck('','userTree','','ckdTree');
                    $.ajax({
                        url: "/common/editUserRole",
                        type: "post",
                        data: "rId=" + id + "&userIds=" + $("#ckdTree").val(),
                        dataType: "json",
                        success: function (data) {
                            $.messager.alert('信息提示', '提交成功！', 'info');
                            $('#user-pz-dialog').dialog('close');
                        },
                        error: function () {
                            $.messager.alert('信息提示', '提交失败！', 'info');
                        },

                    });
                }
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#user-pz-dialog').dialog('close');
                }
            }]
        });
        var setting = {
            check: {
                enable: true
            },
            view: {
                dblClickExpand: false,
                showLine: false,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                }
            }
        };
        var zNodesUser;
        //异步获取人员树
        $.ajax({
            type: 'POST',
            url: '/common/selectUserList',
            dataType: 'json',
            success: function (data) {
                zNodesUser = data.data;
                var t = $("#userTree");
                t = $.fn.zTree.init(t, setting, zNodesUser);
                //获取对应角色的人员
                //根据角色id获取该角色对应的人员
                var uRQuery = {'column': "rid", 'type': 'eq', "value": id};
                var uRQueryJsonArray = [];
                uRQueryJsonArray.push(uRQuery);
                $.ajax({
                    type: 'POST',
                    url: '/user-role/all',
                    dataType: 'json',
                    data: {paramData: JSON.stringify(uRQueryJsonArray)},
                    success: function (data) {
                        zTreeOnAsyncSuccess('', 'userTree', '', '');
                        //    alert(data.data.toString());
                        var treeObj = $.fn.zTree.getZTreeObj("userTree")
                        for (var i = 0; i < data.data.length; i++) {
                            var node = treeObj.getNodeByParam("id", data.data[i].uid);//根据ID找到该节点
                            if (node != null) {
                                treeObj.checkNode(node, true, false);//根据该节点选中
                            }
                        }
                    }
                })
            }
        });
    }

    /**
     * 打开权限选择页面
     */
    function perEdit(id) {
        $('#per-role-form').form('clear');
        $('#per-pz-dialog').dialog({
            closed: false,
            modal: true,
            title: "权限选择",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    onCheck('','perTree','','ckdPreTree');
                    $.ajax({
                        url: "/common/editURolePermission",
                        type: "post",
                        data: "rId=" + id + "&pIds=" + $("#ckdPreTree").val(),
                        dataType: "json",
                        success: function (data) {
                            $.messager.alert('信息提示', '提交成功！', 'info');
                            $('#per-pz-dialog').dialog('close');
                        },
                        error: function () {
                            $.messager.alert('信息提示', '提交失败！', 'info');
                        },

                    });
                }
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#per-pz-dialog').dialog('close');
                }
            }]
        });
        var setting = {
            check: {
                enable: true
            },
            view: {
                dblClickExpand: false,
                showLine: false,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                }
            }
        };
        var zNodesUser;
        //异步获取人员树
        $.ajax({
            type: 'POST',
            url: '/common/zTreePerList',
            dataType: 'json',
            success: function (data) {
                zNodesUser = data.data;
                var t = $("#perTree");
                t = $.fn.zTree.init(t, setting, zNodesUser);
                //获取对应角色的人员
                //根据角色id获取该角色对应的人员
                var uRQuery = {'column': "rid", 'type': 'eq', "value": id};
                var uRQueryJsonArray = [];
                uRQueryJsonArray.push(uRQuery);
                $.ajax({
                    type: 'POST',
                    url: '/role-permission/all',
                    dataType: 'json',
                    data: {paramData: JSON.stringify(uRQueryJsonArray)},
                    success: function (data) {
                        zTreeOnAsyncSuccess('', 'perTree', '', '');
                        //    alert(data.data.toString());
                        var treeObj = $.fn.zTree.getZTreeObj("perTree")
                        for (var i = 0; i < data.data.length; i++) {
                            var node = treeObj.getNodeByParam("id", data.data[i].pid);//根据ID找到该节点
                            if (node != null) {
                                treeObj.checkNode(node, true, false);//根据该节点选中
                            }
                        }
                    }
                })
            }
        });
    }


    /**
     * Name 打开修改窗口
     */
    function jsEdit(id) {
        $('#role-form').form('clear');
        var jsonArray = [];
        if (id != null && id != "") {
            var obj = {'column': "roleid", 'type': 'eq', "value": id};
            jsonArray.push(obj)
        }
        $.ajax({
            type: 'POST',
            url: '/role/find',
            dataType: 'json',
            data: {paramData: JSON.stringify(jsonArray)},
            success: function (data) {
                //alert(data.data.toString());
                $('#role-form').form('load', data.data)
            }
        })
        $('#role-dialog').dialog({
            closed: false,
            modal: true,
            title: "修改信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: edit
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#role-dialog').dialog('close');
                }
            }]
        });
    }

    /**
     * Name 载入数据
     */
    $('#role-datagrid').datagrid({
        url: '/role/list',
        //   loadFilter: pagerFilter,
        //idField:"id",
        rownumbers: true,
        //  singleSelect: false,
        pageSize: 20,
        pagination: true,
        //  multiSort: true,
        fitColumns: true,
        //如果为true，该复选框被选中/取消选中，当用户点击某一行上。如果为false，该复选框仅检查/取消选中，当用户点击完全的复选框。
        checkOnSelect: false,
        fit: true,
        pageList: [10, 20, 50, 100, 150, 200],
        columns: [[
            {checkbox: true},
            {field: 'roleid', title: 'roleid', width: 100, sortable: true, align: 'center', hidden: 'true'},
            {
                field: 'rolename',
                title: '角色名称',
                width: 180,
                sortable: true,
                align: 'center',
                formatter: function (value, data) {
                    return '<a style="color: blue;" href="javascript:jsEdit(\'' + data.roleid + '\')">' + data.rolename + '</a>';
                }
            }, {
                field: 'user',
                title: '人员选择',
                width: 100,
                sortable: true,
                align: 'center',
                formatter: function (value, data) {
                    return '<a style="color: blue;" href="javascript:userEdit(\'' + data.roleid + '\')">人员</a>';
                }
            }, {
                field: 'per',
                title: '权限选择',
                width: 100,
                sortable: true,
                align: 'center',
                formatter: function (value, data) {
                    return '<a style="color: blue;" href="javascript:perEdit(\'' + data.roleid + '\')">权限</a>';
                }
            }
        ]]
    });

    function searchData() {
        var userName = $("#search_userName").val();
        var jsonArray = [];
        if (userName != null && userName != "") {
            var obj = {'column': "rolename", 'type': 'like', "value": userName};
            jsonArray.push(obj)
        }
        return jsonArray;
    }


    function save(url) {
        var formObject = {};
        var formArray = $("#role-form").serializeArray();
        $.each(formArray, function (i, item) {
            formObject[item.name] = item.value;
        });
        // alert(JSON.stringify(formObject));
        $.ajax({
            url: url,
            type: "post",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formObject),
            dataType: "json",
            success: function (data) {
                $.messager.alert('信息提示', '提交成功！', 'info');
                $('#role-dialog').dialog('close');
                $('#role-datagrid').datagrid('reload');
            },
            error: function () {
                $.messager.alert('信息提示', '提交失败！', 'info');
            },

        });
    }

    /**
     * 用于捕获异步加载正常结束的事件回调函数
     * @param event
     * @param treeId
     * @param treeNode
     * @param msg
     */
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var nodes = treeObj.getNodes();
        if (nodes.length > 0) {
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].isParent) {
                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                }
            }
        }
    }

    /**
     * 在zTree选择的时候，记住选择的子节点ID，逗号分隔
     * @param e
     * @param treeId
     * @param treeNode
     */
    function onCheck(e, treeId, treeNode,valueId) {
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        if (treeObj != null) {
            var nodes = treeObj.getCheckedNodes(true);
            v = "";
            for (var i = 0; i < nodes.length; i++) {
                if (!nodes[i].isParent) {
                    v += nodes[i].id + ",";
                }
            }
            $("#"+valueId).val(v);
        }
    }
</script>